package org.tomcat.unit502;

import javax.servlet.ServletException;
import java.io.IOException;
import java.util.HashMap;

public class SimpleContext implements Context {

    private Container parent;

    private Mapper mapper;

    protected HashMap<String, Mapper> mappers = new HashMap();

    private Loader loader;

    protected Pipeline pipeline;

    protected HashMap<String, Container> children = new HashMap();

    private HashMap<String, String> servletMappings = new HashMap();

    public SimpleContext() {
        this.pipeline = new SimplePipeline(this);
        SimpleContextValve valve = new SimpleContextValve();
        valve.setContainer(this);
        pipeline.setBasic(valve);
    }

    @Override
    public String getName() {
        return null;
    }

    @Override
    public void setName(String name) {

    }

    @Override
    public Mapper findMapper(String protocol) {
        if (mapper != null)
            return (mapper);
        else
            synchronized (mappers) {
                return ((Mapper) mappers.get(protocol));
            }
    }

    @Override
    public void addChild(Container child) {
        child.setParent(this);
        this.children.put(child.getName(), child);
    }

    @Override
    public void setParent(Container container) {
        this.parent = container;
    }

    @Override
    public void removeChild(Container child) {
        this.children.remove(child.getName());
    }

    @Override
    public Container findChild(String name) {
        return this.children.get(name);
    }

    @Override
    public Container[] findChildren() {
        return new Container[0];
    }

    @Override
    public void invoke(Request request, Response response) throws IOException, ServletException {
        this.pipeline.invoke(request, response);
    }

    @Override
    public Loader getLoader() {
        return this.loader;
    }

    @Override
    public String findServletMapping(String pattern) {
        return this.servletMappings.get(pattern);
    }

    @Override
    public String[] findServletMappings() {
        String[] res = (String[])this.servletMappings.entrySet().stream().map(item -> item.getValue()).toArray();
        return res;
    }

    @Override
    public void addServletMapping(String pattern, String name) {
        this.servletMappings.put(pattern, name);
    }

    @Override
    public Container map(Request request, boolean update) {
        Mapper mapper = findMapper(request.getRequest().getProtocol());
        if (mapper == null)
            return (null);

        return (mapper.map(request, update));
    }

    public void addMapper(Mapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public void setLoader(Loader loader) {
        this.loader = loader;
    }

    @Override
    public void addValve(Valve valve) {
        this.pipeline.addValve(valve);
    }
}
